package com.gin.kotlin.no_gay_alliance.adapter.replyhistory

import android.content.Context
import android.content.DialogInterface
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.ReplyListActivity
import com.gin.kotlin.no_gay_alliance.activity.replyhistory.ReplyHistoryTaskLogActivity
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.ReplyListArgument
import com.gin.kotlin.no_gay_alliance.argument.ReplyListArgument.Companion.MAX_PAGE
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingRecyclerViewAdapter
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.IntRangeTextWatcher
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.base.ViewUtils.Companion.visible
import com.gin.kotlin.no_gay_alliance.database.entity.ReplyHistoryTask
import com.gin.kotlin.no_gay_alliance.database.entity.ReplyHistoryTask.Status
import com.gin.kotlin.no_gay_alliance.databinding.DialogReplyHistoryTaskBinding
import com.gin.kotlin.no_gay_alliance.databinding.ItemReplyHistoryTaskBinding
import com.gin.kotlin.no_gay_alliance.utils.TimeUtils.Companion.zdtIntoTextView
import java.time.ZonedDateTime

class ReplyHistoryTaskAdapter(context: Context, handler: MyHandler) : AbstractBindingRecyclerViewAdapter<ItemReplyHistoryTaskBinding, ReplyHistoryTask>(context, handler),
    View.OnClickListener {

    override fun onBindViewHolder(holder: ViewHolder<ItemReplyHistoryTaskBinding>, position: Int, b: ItemReplyHistoryTaskBinding, dataModel: ReplyHistoryTask) {
        b.tvTitle.text = dataModel.title
        b.tvRemark.text = dataModel.remark
        b.tvType.text = when (dataModel.type) {
            ReplyHistoryTask.Type.SCANNER -> context.getString(R.string.reply_history_task_type_scanner)
            ReplyHistoryTask.Type.MONITOR -> context.getString(R.string.reply_history_task_type_monitor)
        }
        b.tvStatus.text = when (dataModel.status) {
            Status.PAUSED -> context.getString(R.string.reply_history_task_status_paused)
            Status.IN_PROCESS -> context.getString(R.string.reply_history_task_status_in_process)
            Status.WAITING -> context.getString(R.string.reply_history_task_status_waiting)
            Status.COMPLETED -> context.getString(R.string.reply_history_task_status_completed)
            Status.ERROR -> context.getString(R.string.reply_history_task_status_error)
        }
        val showPauseButton = dataModel.status == Status.IN_PROCESS || dataModel.status == Status.WAITING
        b.ivPause.visibility = visible(showPauseButton)
        b.ivStart.visibility = visible(!showPauseButton)

        zdtIntoTextView(context, dataModel.updatedTime, b.tvUpdatedTime, getAttrColor(R.attr.textColor))

        b.tvProgress.text = when (dataModel.type) {
            ReplyHistoryTask.Type.SCANNER -> "${dataModel.start} / ${dataModel.currentPage} / ${dataModel.end}"
            ReplyHistoryTask.Type.MONITOR -> "最大页: ${dataModel.totalPage}"
        }

        // 删除、修改、打开主题、开始、暂停
        listOf(b.ivEdit, b.ivTopic, b.ivDelete, b.ivPause, b.ivStart, b.layoutContent).forEach {
            it.tag = dataModel
            it.setOnClickListener(this)
        }
    }

    override fun onClick(v: View?) {
        val dataModel = v?.tag as? ReplyHistoryTask ?: return
        val index = data.indexOf(dataModel)
        val dao = App.INSTANCE.database.replyHistoryTaskDao()
        val logDao = App.INSTANCE.database.replyHistoryTaskLogDao()
        val id = dataModel.id
        when (v.id) {
            R.id.layout_content -> ReplyHistoryTaskLogActivity.start(context, id)
            // 暂停
            R.id.iv_pause -> {
                dao.setStatus(id, Status.PAUSED)
                dataModel.status = Status.PAUSED
                handler.post { notifyItemChanged(index) }
            }
            // 开始
            R.id.iv_start -> {
                val status = if (dataModel.type == ReplyHistoryTask.Type.SCANNER) Status.WAITING else Status.IN_PROCESS
                dao.setStatus(id, status)
                dataModel.status = status
                handler.post { notifyItemChanged(index) }
            }
            // 打开主题
            R.id.iv_topic -> ReplyListActivity.startActivity(
                context, ReplyListArgument(
                    ReplyListArgument.Type.LIST,
                    topicId = dataModel.topicId,
                )
            )
            // 修改任务
            R.id.iv_edit -> showUpdateDialog(dataModel)
            // 删除任务
            R.id.iv_delete -> AlertDialogUtils.builder(context, context.getString(R.string.dialog_title_delete_task), listener = { _, which ->
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    dao.del(id)
                    //连带删除日志
                    logDao.delByTaskId(id)
                    removeData(index)
                }
            }).show()
        }
    }

    private fun showUpdateDialog(dataModel: ReplyHistoryTask) {
        val binding = DialogReplyHistoryTaskBinding.inflate(LayoutInflater.from(context))
        val index = data.indexOf(dataModel)
        binding.etTitle.setText(dataModel.title)
        binding.etRemark.setText(dataModel.remark)
        binding.etEnd.setText(dataModel.end.toString())
        binding.etStart.setText(dataModel.start.toString())

        val maxPage = dataModel.totalPage.coerceAtMost(MAX_PAGE)
        binding.etStart.addTextChangedListener(IntRangeTextWatcher(binding.etStart, 1, maxPage))
        binding.etEnd.addTextChangedListener(IntRangeTextWatcher(binding.etEnd, 1, maxPage))
        //页数范围显示隐藏
        binding.spinnerType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val visible = if (position == 0) View.VISIBLE else View.GONE
                listOf(binding.tvLabelPageRange, binding.etStart, binding.etEnd).forEach { it.visibility = visible }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
        }
        binding.spinnerType.setSelection(if (dataModel.type == ReplyHistoryTask.Type.SCANNER) 0 else 1)


        AlertDialogUtils.builder(context, "修改回复历史任务", contentView = binding.root, listener = { _, which ->
            if (which == DialogInterface.BUTTON_POSITIVE) {
                val task = dataModel.copy(
                    title = binding.etTitle.text.toString(),
                    remark = binding.etRemark.text.toString(),
                    type = if (binding.spinnerType.selectedItemPosition == 0) ReplyHistoryTask.Type.SCANNER else ReplyHistoryTask.Type.MONITOR,
                    status = Status.WAITING,
                    start = binding.etStart.text.toString().toIntOrNull() ?: 0,
                    end = binding.etEnd.text.toString().toIntOrNull() ?: 0,
                    updatedTime = ZonedDateTime.now()
                )
                App.INSTANCE.database.replyHistoryTaskDao().update(task)
                data[index] = task
                handler.post { notifyItemChanged(index) }
            }
        }).show()
    }
}